package com.kingwang.training.designpattern.interpreter.bo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * @author King
 */
public class Context {
    public Double calculate() throws IOException {
        String expressionStr = inputExpressionStr();

        Map<String, Double> variables = inputVariableValues(expressionStr);

        Calculator calculator = new Calculator(expressionStr);

        return calculator.calculate(variables);
    }

    private String inputExpressionStr() throws IOException {
        System.out.println("请输入表达式：");
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        return reader.readLine();
    }

    private Map<String, Double> inputVariableValues(String expressionStr) throws IOException {
        Map<String, Double> values = new HashMap<>();

        for (char ch : expressionStr.toCharArray()) {
            if (ch != '+' && ch != '-' && ch != ' ') {
                String key = String.valueOf(ch);

                //这里需要防止同样的元素被重复赋值导致值被覆盖
                if (!values.containsKey(key)) {
                    System.out.println("请输入" + key + "的值：");
                    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
                    Double value = Double.valueOf(reader.readLine());
                    values.put(key, value);
                }
            }
        }

        return values;
    }
}
